#!/usr/bin/env node

/**
 * 项目完整性验证脚本
 * 检查项目结构、依赖、配置等是否完整
 */

import fs from 'fs';
import path from 'path';

class ProjectValidator {
  constructor() {
    this.errors = [];
    this.warnings = [];
    this.success = [];
  }

  // 检查文件是否存在
  checkFileExists(filePath, description) {
    if (fs.existsSync(filePath)) {
      this.success.push(`✅ ${description}: ${filePath}`);
      return true;
    } else {
      this.errors.push(`❌ ${description} 缺失: ${filePath}`);
      return false;
    }
  }

  // 检查目录是否存在
  checkDirectoryExists(dirPath, description) {
    if (fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory()) {
      this.success.push(`✅ ${description}: ${dirPath}`);
      return true;
    } else {
      this.errors.push(`❌ ${description} 缺失: ${dirPath}`);
      return false;
    }
  }

  // 检查 package.json 配置
  checkPackageJson() {
    const packagePath = './package.json';
    if (!this.checkFileExists(packagePath, 'package.json')) return;

    try {
      const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
      
      // 检查必要的脚本
      const requiredScripts = ['dev', 'build', 'lint', 'test'];
      requiredScripts.forEach(script => {
        if (packageJson.scripts && packageJson.scripts[script]) {
          this.success.push(`✅ NPM 脚本 "${script}" 已配置`);
        } else {
          this.warnings.push(`⚠️ NPM 脚本 "${script}" 未配置`);
        }
      });

      // 检查必要的依赖
      const requiredDeps = [
        'react', 'react-dom', 'react-router-dom', 'zustand', 
        'chroma-js', 'localforage', 'tailwindcss'
      ];
      
      const allDeps = {
        ...packageJson.dependencies,
        ...packageJson.devDependencies
      };

      requiredDeps.forEach(dep => {
        if (allDeps[dep]) {
          this.success.push(`✅ 依赖 "${dep}" 已安装`);
        } else {
          this.errors.push(`❌ 依赖 "${dep}" 缺失`);
        }
      });

    } catch (error) {
      this.errors.push(`❌ package.json 解析失败: ${error.message}`);
    }
  }

  // 检查 TypeScript 配置
  checkTypeScriptConfig() {
    this.checkFileExists('./tsconfig.json', 'TypeScript 配置');
    this.checkFileExists('./tsconfig.node.json', 'TypeScript Node 配置');
  }

  // 检查构建工具配置
  checkBuildConfig() {
    this.checkFileExists('./vite.config.ts', 'Vite 配置');
    this.checkFileExists('./tailwind.config.js', 'Tailwind CSS 配置');
    this.checkFileExists('./postcss.config.js', 'PostCSS 配置');
  }

  // 检查代码质量工具配置
  checkQualityTools() {
    this.checkFileExists('./.eslintrc.cjs', 'ESLint 配置');
    this.checkFileExists('./.prettierrc', 'Prettier 配置');
    this.checkFileExists('./jest.config.js', 'Jest 配置');
  }

  // 检查项目结构
  checkProjectStructure() {
    const requiredDirs = [
      './src',
      './src/components',
      './src/components/ui',
      './src/components/color',
      './src/components/layout',
      './src/pages',
      './src/stores',
      './src/services',
      './src/utils',
      './src/types',
      './src/__tests__'
    ];

    requiredDirs.forEach(dir => {
      this.checkDirectoryExists(dir, `目录结构`);
    });
  }

  // 检查核心文件
  checkCoreFiles() {
    const coreFiles = [
      './src/main.tsx',
      './src/App.tsx',
      './src/index.css',
      './index.html',
      './README.md'
    ];

    coreFiles.forEach(file => {
      this.checkFileExists(file, '核心文件');
    });
  }

  // 检查组件文件
  checkComponents() {
    const componentFiles = [
      './src/components/ui/Button.tsx',
      './src/components/ui/Input.tsx',
      './src/components/ui/Modal.tsx',
      './src/components/ui/LoadingSpinner.tsx',
      './src/components/color/ColorPicker.tsx',
      './src/components/layout/Header.tsx',
      './src/components/layout/Sidebar.tsx',
      './src/components/Layout.tsx'
    ];

    componentFiles.forEach(file => {
      this.checkFileExists(file, '组件文件');
    });
  }

  // 检查页面文件
  checkPages() {
    const pageFiles = [
      './src/pages/Dashboard.tsx',
      './src/pages/ColorPickerPage.tsx',
      './src/pages/RecommendationsPage.tsx',
      './src/pages/HistoryPage.tsx',
      './src/pages/AnalyticsPage.tsx',
      './src/pages/SettingsPage.tsx'
    ];

    pageFiles.forEach(file => {
      this.checkFileExists(file, '页面文件');
    });
  }

  // 检查服务文件
  checkServices() {
    const serviceFiles = [
      './src/services/storage.ts',
      './src/services/recommendation.ts'
    ];

    serviceFiles.forEach(file => {
      this.checkFileExists(file, '服务文件');
    });
  }

  // 检查状态管理文件
  checkStores() {
    const storeFiles = [
      './src/stores/index.ts',
      './src/stores/userStore.ts',
      './src/stores/colorStore.ts',
      './src/stores/recommendationStore.ts',
      './src/stores/hooks.ts'
    ];

    storeFiles.forEach(file => {
      this.checkFileExists(file, '状态管理文件');
    });
  }

  // 检查工具文件
  checkUtils() {
    const utilFiles = [
      './src/utils/index.ts',
      './src/utils/color.ts'
    ];

    utilFiles.forEach(file => {
      this.checkFileExists(file, '工具文件');
    });
  }

  // 检查类型定义文件
  checkTypes() {
    const typeFiles = [
      './src/types/index.ts',
      './src/types/components.ts',
      './src/types/api.ts'
    ];

    typeFiles.forEach(file => {
      this.checkFileExists(file, '类型定义文件');
    });
  }

  // 检查测试文件
  checkTests() {
    const testFiles = [
      './src/__tests__/setup.ts',
      './src/__tests__/utils/color.test.ts',
      './src/__tests__/components/ui/Button.test.tsx'
    ];

    testFiles.forEach(file => {
      this.checkFileExists(file, '测试文件');
    });
  }

  // 运行所有检查
  validate() {
    console.log('🔍 开始项目完整性验证...\n');

    console.log('📦 检查 package.json 配置...');
    this.checkPackageJson();

    console.log('\n⚙️ 检查配置文件...');
    this.checkTypeScriptConfig();
    this.checkBuildConfig();
    this.checkQualityTools();

    console.log('\n📁 检查项目结构...');
    this.checkProjectStructure();

    console.log('\n📄 检查核心文件...');
    this.checkCoreFiles();

    console.log('\n🧩 检查组件文件...');
    this.checkComponents();

    console.log('\n📱 检查页面文件...');
    this.checkPages();

    console.log('\n🔧 检查服务文件...');
    this.checkServices();

    console.log('\n🗃️ 检查状态管理文件...');
    this.checkStores();

    console.log('\n🛠️ 检查工具文件...');
    this.checkUtils();

    console.log('\n📝 检查类型定义文件...');
    this.checkTypes();

    console.log('\n🧪 检查测试文件...');
    this.checkTests();

    this.printResults();
  }

  // 打印结果
  printResults() {
    console.log('\n' + '='.repeat(60));
    console.log('📊 验证结果汇总');
    console.log('='.repeat(60));

    if (this.success.length > 0) {
      console.log(`\n✅ 成功项目 (${this.success.length}):`);
      this.success.forEach(item => console.log(`   ${item}`));
    }

    if (this.warnings.length > 0) {
      console.log(`\n⚠️ 警告项目 (${this.warnings.length}):`);
      this.warnings.forEach(item => console.log(`   ${item}`));
    }

    if (this.errors.length > 0) {
      console.log(`\n❌ 错误项目 (${this.errors.length}):`);
      this.errors.forEach(item => console.log(`   ${item}`));
    }

    console.log('\n' + '='.repeat(60));
    
    if (this.errors.length === 0) {
      console.log('🎉 项目验证通过！所有必要文件和配置都已就位。');
      console.log('📝 建议接下来的步骤:');
      console.log('   1. 运行 npm install 安装依赖');
      console.log('   2. 运行 npm run dev 启动开发服务器');
      console.log('   3. 运行 npm run test 执行测试');
      console.log('   4. 运行 npm run build 构建生产版本');
    } else {
      console.log('🚨 项目验证失败！请修复上述错误后重新验证。');
      process.exit(1);
    }
  }
}

// 运行验证
const validator = new ProjectValidator();
validator.validate();